<style lang="less">
#areaMap {
  width: 100%;
  height: 340px;
}
</style>
<template>
  <div style="background:#fff">

    <div class="search">
      <Row>
        <Col>
        <Card>
          <Row>
            <Form ref="searchForm"
                  :model="searchForm"
                  inline
                  :label-width="70"
                  class="search-form">
              <Form-item label="区域名称">
                <Input type="text"
                       v-model="searchForm.areaName"
                       :clearable="true"
                       placeholder="请输入区域名称"
                       style="width: 200px" />
              </Form-item>
              <Form-item label="区域类型">
                <Select v-model="searchForm.areaType"
                        :transfer="true"
                        :clearable="true"
                        style="width: 200px">
                  <Option v-for="item in fenceDict"
                          :value="item.value"
                          :key="item.value">{{ item.label }}</Option>
                </Select>
              </Form-item>
              <Form-item style="margin-left:-35px;"
                         class="br">
                <Button @click="handleSearch"
                        type="primary"
                        icon="ios-search">搜索</Button>
                <Button @click="handleReset">重置</Button>
              </Form-item>
            </Form>
          </Row>
          <Row class="operation">
            <Button @click="add"
                    type="primary"
                    icon="md-add"
                    v-has="'add'">新增</Button>
            <circleLoading v-if="operationLoading" />
          </Row>
          <Row>
            <Alert show-icon>
              已选择
              <span class="select-count">{{selectCount}}</span> 项
              <a class="select-clear"
                 @click="clearSelectAll">清空</a>
            </Alert>
          </Row>
          <Row>
            <Table :loading="loading"
                   border
                   :columns="columns"
                   :data="data"
                   sortable="custom"
                   @on-sort-change="changeSort"
                   @on-selection-change="showSelect"
                   ref="table"></Table>
          </Row>
          <Row type="flex"
               justify="end"
               class="page">
            <Page :current="searchForm.current"
                  :total="total"
                  :page-size="searchForm.size"
                  @on-change="changePage"
                  @on-page-size-change="changePageSize"
                  :page-size-opts="[10,20,50,100]"
                  size="small"
                  show-total
                  show-elevator
                  show-sizer></Page>
          </Row>
        </Card>
        </Col>
      </Row>
      <Modal :title="modalTitle"
             v-model="areaModalVisible"
             :mask-closable="false"
             :width="1000"
             :styles="{top: '30px'}">
        <div id="areaMap"></div>

        <Form ref="areaForm"
              :model="areaForm"
              :label-width="110"
              :rules="areaFormValidate"
              style="padding-top:20px;">
          <Row>
            <Col :span="12">
            <FormItem label="区域名称"
                      prop="areaName">
              <Input v-model="areaForm.areaName"
                     style="width:240px;" />
            </FormItem>
            </Col>
            <Col :span="12">
            <FormItem label="区域类型"
                      prop="areaType">
              <RadioGroup v-model="areaForm.areaType"
                          @on-change="radioChange"
                          type="button">
                <Radio v-for="item in fenceDict"
                       :value="item.value"
                       :key="item.value"
                       :label="item.value">{{item.label}}</Radio>
              </RadioGroup>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col :span="12">
            <FormItem label="坐标点"
                      prop="latlng">
              <Input v-model="areaForm.latlng"
                     placeholder="在地图上绘制获得"
                     style="width:240px;"
                     :readonly="true" />
            </FormItem>
            </Col>
            <Col :span="12">
            <FormItem label="半径（米）"
                      v-if="areaForm.areaType==1">
              <Input v-model="areaForm.radius"
                     placeholder="在地图上绘制获得"
                     style="width:240px;"
                     :readonly="true" />
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col :span="12">
            <FormItem label="所属企业"
                      prop="companyId">
              <Select v-model="areaForm.companyId"
                      style="width:240px;"
                      :clearable="true"
                      :transfer="true">

                <Option v-for="item in companySelect"
                        :value="item.value"
                        :key="item.value">{{ item.label }}
                </Option>
              </Select>
            </FormItem>

            </Col>
            <Col :span="12">
            <FormItem label="区域类别">
              <Select v-model="areaForm.areaStyle"
                      style="width:240px;"
                      :clearable="true"
                      :transfer="true">

                <Option v-for="item in areaStyleDict"
                        :value="item.value"
                        :key="item.value">{{ item.label }}
                </Option>
              </Select>
            </FormItem>

            </Col>
          </Row>
        </Form>
        <div slot="footer">
          <Button type="warning"
                  icon="ios-brush"
                  :loading="submitLoading"
                  @click="startDraw">开始绘制</Button>
          <Button type="primary"
                  :loading="submitLoading"
                  @click="submitArea">提交</Button>
          <Button type="default"
                  @click="areaModalVisible = false">取消</Button>
        </div>
      </Modal>
    </div>

  </div>

</template>

<script>
import AMap from 'AMap'
let mouseTool = null
import {
  getAreaPageList,
  addArea,
  editArea,
  deleteArea,
  getCompanySelect
} from '@/api/operate'
import circleLoading from '../../my-components/circle-loading.vue'
import { fenceDict, areaStyleDict } from '@/libs/dict'
export default {
  name: 'area-manage',
  components: {
    circleLoading
  },
  data() {
    return {
      fenceDict: fenceDict,
      areaStyleDict: areaStyleDict,
      companySelect: [],
      loading: true,
      operationLoading: false,
      searchForm: {
        areaName: '',
        areaType: '',
        areaStyle: '',

        current: 1,
        size: 20,
        sort: 'createTime',
        order: 'desc'
      },
      areaModalVisible: false,
      modalType: 0,
      selectCount: 0,
      selectList: [],
      modalTitle: '',
      areaForm: {
        customAreaId: '',
        areaName: '',
        areaType: 2,
        latlng: '',
        radius: '',
        companyId: ''
      },
      areaFormValidate: {
        areaName: [
          { required: true, message: '区域名称不能为空', trigger: 'blur' }
        ],
        latlng: [{ required: true, message: '请绘制区域', trigger: 'blur' }],
        companyId: [
          {
            required: true,
            message: '请选择企业',
            trigger: 'change',
            type: 'number'
          }
        ]
      },
      submitLoading: false,
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '区域名称',
          key: 'areaName',
          minWidth: 150,
          sortable: true
        },
        {
          title: '区域类型',
          key: 'areaType',
          minWidth: 180,
          render: (h, params) => {
            return h(
              'span',
              this.fenceDict.find(item => {
                return item.value == params.row.areaType
              }).label
            )
          }
        },
        {
          title: '区域类别',
          key: 'areaStyle',
          width: 180,
          render: (h, params) => {
            let areaStyle = ''
            if (params.row.areaStyle) {
              areaStyle = this.areaStyleDict.find(item => {
                return item.value == params.row.areaStyle
              }).label
            }
            return h('span', areaStyle)
          }
        },
        {
          title: '所属企业',
          key: 'companyName',
          minWidth: 240,
          sortable: true
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          align: 'center',
          fixed: 'right',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'warning',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  directives: [
                    {
                      name: 'has',
                      value: 'edit'
                    }
                  ],
                  on: {
                    click: () => {
                      this.edit(params.row)
                    }
                  }
                },
                '编辑'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  directives: [
                    {
                      name: 'has',
                      value: 'delete'
                    }
                  ],
                  on: {
                    click: () => {
                      this.remove(params.row)
                    }
                  }
                },
                '删除'
              )
            ])
          }
        }
      ],
      data: [],
      total: 0,
      map: null
    }
  },
  methods: {
    init() {
      this.getAreaList()
      this.mapInit()
      this.getCompanySelectList()
    },
    mapInit() {
      this.map = new AMap.Map('areaMap', {
        resizeEnable: true,
        zoom: 5,
        zooms: [3, 20],
        expandZoomRange: true,
        mapStyle: 'amap://styles/fresh'
      })
      let self = this
      this.map.plugin(['AMap.MapType'], function() {
        //地图类型切换
        var type = new AMap.MapType({
          defaultType: 0 //使用2D地图
        })
        self.map.addControl(type)
      })
      this.map.plugin(['AMap.ToolBar'], function() {
        //加载工具条
        var tool = new AMap.ToolBar()
        self.map.addControl(tool)
      })
      this.map.plugin(['AMap.MouseTool'], function() {
        //鼠标工具插件
        mouseTool = new AMap.MouseTool(self.map)
      })

      AMap.event.addListener(mouseTool, 'draw', function(event) {
        // event.obj 为绘制出来的覆盖物对象
        let drawObj = event.obj
        let points = drawObj.getPath()
        let newpoints = []
        if (self.areaForm.areaType == 1) {
          let centerPoint = drawObj.getCenter()
          newpoints = [[centerPoint.lat, centerPoint.lng]]
          self.areaForm.radius = drawObj.getRadius()
          //圆形
        } else if (self.areaForm.areaType == 2) {
          newpoints = [
            [points[0].lat, points[0].lng],
            [points[2].lat, points[2].lng]
          ]
          //矩形
        } else if (self.areaForm.areaType == 3) {
          //多边形
          points.forEach(item => {
            newpoints.push([item.lat, item.lng])
          })
        }
        self.areaForm.latlng = newpoints.join('|')

        mouseTool.close(false)
        self.$Message.info('绘制完成')
      })
    },
    getCompanySelectList() {
      getCompanySelect().then(res => {
        if (res.code == 0) {
          this.companySelect = res.data
        }
      })
    },
    startDraw() {
      this.map.clearMap()
      let infoMsg = ''
      if (this.areaForm.areaType == 1) {
        //圆形
        infoMsg = '点击鼠标左键确定中心点，移动确定半径，松开鼠标完成'
        mouseTool.circle({
          strokeColor: '#FF33FF',
          strokeOpacity: 1,
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillColor: '#1791fc',
          fillOpacity: 0.4,
          strokeStyle: 'solid'
          // 线样式还支持 'dashed'
          // strokeDasharray: [30,10],
        })
      } else if (this.areaForm.areaType == 2) {
        //矩形
        infoMsg = '点击鼠标左键确定左上角，松开鼠标完成确定矩形右下角'
        mouseTool.rectangle({
          strokeColor: 'red',
          strokeOpacity: 0.5,
          strokeWeight: 6,
          fillColor: 'blue',
          fillOpacity: 0.5,
          // strokeStyle还支持 solid
          strokeStyle: 'solid'
          // strokeDasharray: [30,10],
        })
      } else if (this.areaForm.areaType == 3) {
        //多边形
        infoMsg = '点击鼠标左键确定多边形的角，右键完成绘制'
        mouseTool.polygon({
          strokeColor: '#FF33FF',
          strokeOpacity: 1,
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillColor: '#1791fc',
          fillOpacity: 0.4,
          // 线样式还支持 'dashed'
          strokeStyle: 'solid'
          // strokeStyle是dashed时有效
          // strokeDasharray: [30,10],
        })
      }
      this.$Message.info(infoMsg)
    },
    changePage(v) {
      this.searchForm.current = v
      this.getAreaList()
      this.clearSelectAll()
    },
    changePageSize(v) {
      this.searchForm.size = v
      this.getAreaList()
    },
    getAreaList() {
      // 多条件搜索
      this.loading = true
      getAreaPageList(this.searchForm).then(res => {
        this.loading = false
        if (res.code == 0) {
          this.data = res.data.records
          this.total = res.data.total
        }
      })
    },
    handleSearch() {
      this.searchForm.current = 1
      this.searchForm.size = 20
      this.getAreaList()
    },
    handleReset() {
      this.$refs.searchForm.resetFields()
      this.searchForm.areaName = ''
      this.searchForm.areaType = ''
      this.searchForm.current = 1
      this.searchForm.size = 20
      // 重新加载数据
      this.getAreaList()
    },
    showSelect(e) {
      this.selectList = e
      this.selectCount = e.length
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false)
    },
    changeSort(e) {
      this.searchForm.sort = e.key
      this.searchForm.order = e.order
      if (e.order == 'normal') {
        this.searchForm.order = ''
      }
      this.getAreaList()
    },
    submitArea() {
      this.$refs.areaForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          let params = JSON.parse(JSON.stringify(this.areaForm))
          if (this.modalType == 0) {
            addArea(params).then(res => {
              this.submitLoading = false
              if (res.code == 0) {
                this.$Message.success('操作成功')
                this.getAreaList()
                this.areaModalVisible = false
              } else {
                this.$Message.error(res.msg)
              }
            })
          } else {
            editArea(params).then(res => {
              this.submitLoading = false
              if (res.code == 0) {
                this.$Message.success('操作成功')
                this.getAreaList()
                this.areaModalVisible = false
              } else {
                this.$Message.error(res.msg)
              }
            })
          }
        }
      })
    },
    add() {
      this.modalType = 0
      this.modalTitle = '新增区域'
      this.map.clearMap()
      this.areaForm = {
        customAreaId: '',
        areaName: '',
        areaType: 2,
        latlng: '',
        radius: '',
        companyId: ''
      }
      this.areaModalVisible = true
    },
    edit(v) {
      this.modalType = 1
      this.modalTitle = '编辑区域'
      this.$refs.areaForm.resetFields()
      for (let attr in v) {
        if (v[attr] == null) {
          v[attr] = ''
        }
      }
      this.areaForm = JSON.parse(JSON.stringify(v))
      this.map.clearMap()
      if (v.areaType == 1) {
        // 构造矢量圆形
        let circlePoints = v.latlng.split(',')
        var circle = new AMap.Circle({
          center: new AMap.LngLat(circlePoints[1], circlePoints[0]), // 圆心位置
          radius: v.radius, //半径
          strokeColor: '#FF33FF',
          strokeOpacity: 1,
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillColor: '#1791fc',
          fillOpacity: 0.4,
          strokeStyle: 'solid'
        })
        this.map.add(circle)
        this.map.setFitView()
      } else if (v.areaType == 2) {
        let recPoints = v.latlng.split('|')

        // 构造矢量矩形  数据库存储的是左上和右下
        var southWest = new AMap.LngLat(
          recPoints[0].split(',')[1],
          recPoints[1].split(',')[0]
        )
        var northEast = new AMap.LngLat(
          recPoints[1].split(',')[1],
          recPoints[0].split(',')[0]
        )

        var bounds = new AMap.Bounds(southWest, northEast)

        var rectangle = new AMap.Rectangle({
          bounds: bounds,
          strokeColor: 'red',
          strokeOpacity: 0.5,
          strokeWeight: 6,
          fillColor: 'blue',
          fillOpacity: 0.5,
          // strokeStyle还支持 solid
          strokeStyle: 'solid'
        })
        this.map.add(rectangle)
        this.map.setFitView()
      } else if (v.areaType == 3) {
        // 构造矢量多边形
        let polyPoints = v.latlng.split('|')
        let path = []
        polyPoints.forEach(poly => {
          let item = poly.split(',')
          path.push([item[1], item[0]])
        })

        var polygon = new AMap.Polygon({
          path: path,
          strokeColor: '#FF33FF',
          strokeOpacity: 1,
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillColor: '#1791fc',
          fillOpacity: 0.4,
          // 线样式还支持 'dashed'
          strokeStyle: 'solid'
        })

        this.map.add(polygon)
        this.map.setFitView()
      }
      this.areaModalVisible = true
    },
    remove(v) {
      this.$Modal.confirm({
        title: '确认删除',
        content: '您确认要删除区域 ' + v.areaName + ' ?',
        loading: true,
        onOk: () => {
          deleteArea(v.customAreaId).then(res => {
            this.$Modal.remove()
            if (res.code == 0) {
              this.$Message.success('删除成功')
              this.getAreaList()
            } else {
              this.$Message.error(res.msg)
            }
          })
        }
      })
    },
    radioChange(v) {
      this.map.clearMap()
    }
  },
  mounted() {
    this.init()
  }
}
</script>